package com.ruoyi.xdata.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.xdata.domain.XdataVo;
import com.ruoyi.xdata.mapper.XdataMapper;
import com.ruoyi.xdata.service.IXdataService;

/**
 * 模型Service业务层处理
 * 
 * @author yepanpan
 * @date 2020-12-29
 */
@Service
public class XdataServiceImpl implements IXdataService 
{
    @Autowired
    private XdataMapper xdataMapper;


    /**
     * 查询一条数据
     * 
     * @param xdataModel 模型
     * @return 模型集合
     */
	@Override
    public Map findData(XdataVo data) {
    	return xdataMapper.findData(data);
    }
    
	@Override
	public List<Map> selectList(XdataVo data) {
		return xdataMapper.selectList(data);
	}
	 
	@Override
	public List<Map> selectData(String sql) {
		return xdataMapper.selectData(sql);
	}	

	@Override
    public int updateData(String sql) {
		return xdataMapper.updateData(sql);
    }

	@Override
    public int insertData(String sql) {
		return xdataMapper.insertData(sql);    	
    }
    
	@Override
	public int updateData(XdataVo data) {
		if(data.getId() == null) {
			data.setId(data.getData().get("id").toString());
		}
		if(data.getId() == null) return -1;
		
		StringBuilder sb = new StringBuilder();
		sb.append("UPDATE ").append(data.getTable()).append(" SET ");
		for(String k:data.getData().keySet()) {
			sb.append(k).append("=").append("'").append(data.getData().get(k).toString()).append("',");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append(" WHERE id='").append(data.getId()).append("'");
		return xdataMapper.updateData(sb.toString());
	}

	@Override
	public int insertData(XdataVo data) {
		StringBuilder sb = new StringBuilder();
		sb.append("INSERT INTO ").append(data.getTable()).append(" ( ");
		for(String k:data.getData().keySet()) {
			sb.append(k).append(",");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append(" ) VALUES (");
		for(String k:data.getData().keySet()) {
			sb.append("'").append(data.getData().get(k).toString()).append("',");
		}
		sb.deleteCharAt(sb.length()-1).append(")");
		return xdataMapper.insertData(sb.toString());
	}

	@Override
	public int deleteData(XdataVo data) {
		if(data.getId() == null) return 0;

		String[] ids = data.getId().split(",");
		StringBuilder sb = new StringBuilder();
		sb.append("DELETE FROM ").append(data.getTable()).append(" WHERE id IN ( ");
		for(String id : ids) {
			sb.append("'").append(id).append("',");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append(" )");
		return xdataMapper.deleteData(sb.toString());
		
	}

}
